package sh.service.impl;

import sh.dao.BookDao;
import sh.dto.BookBoardDto;
import sh.model.Book;
import sh.orm.ProxyFactory;
import sh.orm.Session;
import sh.orm.SessionFactory;
import sh.orm.query.*;
import sh.service.BookService;
import sh.spring.annotation.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @author lqq
 * @date 2019/1/24
 */
@Service
public class BookServiceImpl implements BookService {


    /** 使用返回代理类 TODO 通过spring自动管理 */
    //@Autowired
    //BookDao<Book> bookDao;
    BookDao<Book> bookDao = ProxyFactory.getDao(BookDao.class);


    @Override
    public void add(Book book){
        SessionFactory.getInstance().getSession().save(book);
    }

    /**
     * 删除书本
     * @param id
     */
    @Override
    public void remove(Long id){

        SessionFactory.getInstance().getSession().delete(id,Book.class);
    }

    /**
     * 编辑书本信息
     * @param book
     */
    @Override
    public void edit(Book book){
        SessionFactory.getInstance().getSession().update(book);
    }

    /**
     * 向数据库里插入一条book的记录
     * @param book
     * @param upFile
     * @return
     */
    @Override
    public boolean save(Book book,File upFile)  {

        Connection conn = SessionFactory.getInstance().getSession().getConnection();
        PreparedStatement pstmt = null;

        try {
            // 将自动提交设置为false，也就是讲所有的插入语句放入一个transaction里
            conn.setAutoCommit(false);

            String sql = "insert into t_book values(seq_id.nextval,?,?,?,?,?,sysdate,?,?)";
            //String sql = "insert into t_book values (?,null,?,null,null,null,null,null)";
            pstmt = conn.prepareStatement(sql);

            //testSQL: insert into t_book values (seq_id.nextval,null,'hh',null,null,null,null,null,null);

            //pstmt.setInt(1, book.getId());

            pstmt.setString(2, book.getName());

            pstmt.setString(3, book.getAuthor());
            pstmt.setString(4, book.getPressName());
            //日期用new Date(long)
            //pstmt.setDate(5, book.getPressDate());

            pstmt.setBigDecimal(6, book.getPrice());
            //将图片文件转换为二进制流存入数据库
            InputStream photoStream = null;
            try {
                if(upFile == null){
                    System.out.println("file is null");
                }
                photoStream = new FileInputStream(upFile);
            } catch (FileNotFoundException e) {

                e.printStackTrace();
            }
            pstmt.setBinaryStream(7, photoStream, (int)upFile.length());

            pstmt.executeUpdate();

            conn.commit();
            conn.setAutoCommit(true);

            pstmt.close();
            conn.close();
            // 如果没有异常，说明提交成功，返回true
            return true;

        } catch (SQLException e) {

            e.printStackTrace();
            // 如果有异常，说明没有成功，返回false
            return false;
        } finally {
        }

    }

    @Override
    public List<Book> getAll() {
        return SessionFactory.getInstance().getSession().getAll(Book.class);
    }

    @Override
    public List<Book> getByUserId(Long userId) {
        QueryCondition queryCondition = new QueryCondition();
        Condition condition = new Condition(Book.USER_ID,ConditionConst.EQUAL,userId);
        queryCondition.add(condition);
        return SessionFactory.getInstance().getSession().selectByQueryCondition(queryCondition,Book.class);
    }

    @Override
    public Page<Book> getPageByUserId(Long userId, Pageable pageable) {
        QueryCondition queryCondition = new QueryCondition();
        Condition condition = new Condition(Book.USER_ID,ConditionConst.EQUAL,userId);
        queryCondition.add(condition);
        Session session = SessionFactory.getInstance().getSession();
        return session.selectPageByQueryCondition(queryCondition,pageable,Book.class);
    }

    @Override
    public Book get(Long id) {
        return SessionFactory.getInstance().getSession().getById(id,Book.class);
    }

    @Override
    public List<BookBoardDto> getPrevious(int n) {
        return bookDao.getPrevious(n);
    }

    @Override
    public List<Book> getByBookName(String bookName) {
        QueryCondition queryCondition = new QueryCondition();
        Condition condition = new Condition(Book.NAME , ConditionConst.EQUAL , bookName);
        queryCondition.add(condition);
        return SessionFactory.getInstance().getSession().selectByQueryCondition(queryCondition,Book.class);
    }

    @Override
    public List<Book> getByAuthor(String author) {
        QueryCondition queryCondition = new QueryCondition();
        Condition condition = new Condition(Book.PRICE , ConditionConst.EQUAL , author);
        queryCondition.add(condition);
        return SessionFactory.getInstance().getSession().selectByQueryCondition(queryCondition,Book.class);
    }

    @Override
    public List<Book> getByPriceLowerThan(float price) {
        QueryCondition queryCondition = new QueryCondition();
        Condition condition = new Condition(Book.PRICE , ConditionConst.LITTLE , price);
        queryCondition.add(condition);
        return SessionFactory.getInstance().getSession().selectByQueryCondition(queryCondition,Book.class);
    }

    @Override
    public List<Book> getByPrice(float min,float max){
        QueryCondition queryCondition = new QueryCondition();
        Condition condition = new Condition(Book.PRICE , ConditionConst.LITTLE_EQUAL , max);
        Condition condition2 = new Condition(Book.PRICE , ConditionConst.GREAT_EQUAL , min);
        queryCondition.add(condition)
                .add(condition2);
        return SessionFactory.getInstance().getSession().selectByQueryCondition(queryCondition , Book.class);
    }

}
